<?php

namespace app\astrologer\controller\v4;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrExerciseRecord;
use app\common\cachemodel\ZlcrAstrNotAnswerQuestion;
use app\common\cachemodel\ZlcrAstrQuestionNote;
use app\common\cachemodel\ZlcrCustomReportQuestion;
use app\common\cachemodel\ZlcrCustomReportQuestionComment;
use app\common\lib\Util;
use think\Db;
use think\Env;

class Task extends AstrAuth
{
    public function assignTaskChange()
    {
        $status = input('status/d', 0);

        if (!in_array($status, [0, 1], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zlcrAstrModel = new ZlcrAstr();
        if ($status === 1)
        {
            if ((int)$this->astrInfo['check_status'] !== 40)
            {
                return show(config('code.error'), '账号状态异常，开启接单失败~');
            }

            $authStatus = $this->astrInfo['auth_status'];
            if ($authStatus['custom_report'] !== 1)
            {
                return show(config('code.error'), '账号状态异常，开启接单失败~');
            }

            if ((int)$this->astrInfo['status'] === 2 || $this->astrInfo['pause_time'] - $this->request->time() > 0)
            {
                return show(config('code.error'), '账号已被冻结，开启接单失败~');
            }

            if (!isset($this->astrInfo['extend']['is_complete_information']))
            {
                return show(config('code.error'), '请完善资料后再开启接单状态～');
            }

            $update = ['custom_report_status' => 1];
        } else
        {
            $update = ['custom_report_status' => 0];
        }
        $zlcrAstrModel->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], $update);

        return show(config('code.success'), '请求成功');
    }


    /**
     * 获取占星师任务列表
     * @method GET
     * @throws Exception
     */
    public function list()
    {
        $question = trim(input('question/s', ''));
        // h5
        $param['start_time'] = $this->request->param('start_time/s', 0);
        $param['end_time'] = $this->request->param('end_time/s', 0);
        // pc
        $rangeTime = input('range_time/a', []);
        $qtype = input('qtype/a', []);
        $param['status'] = $this->request->only(['status']);
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $sort = input('sort/s', 'astr_receiving_time DESC');// 默认接单时间倒序
        $isIndex = input('index/d', 0);

        $astrQuestionNoteModel = new ZlcrAstrQuestionNote();

        if ($isIndex)
        {
            $authStatus = $this->astrInfo['auth_status'];
            if ($authStatus['custom_report'] !== 1)
            {   // 还未认证
                $astrAnswerModel = new ZlcrAstrExerciseRecord();
                $imgHost = Env::get('host.photo');
                $astrAnswerInfo = $astrAnswerModel->getExerciseInfo($this->astrInfo['id'], 1);   // 1=>定制报告 2=>问答三合一 3=>问答星盘 4=>问答骰子 5=>问答塔罗
                if ($astrAnswerInfo && (int)$astrAnswerInfo['status'] === 2 && $this->request->time() - $astrAnswerInfo['fail_time'] > 86400)
                {
                    $astrAnswerInfo = null; // 失败24小时后允许重新考试
                }
                $res = $astrAnswerModel->getExerciseRes2($astrAnswerInfo);
                $customReport1Status = $res[1]['status']; // 考试状态
                $customReport1Tips = $res[1]['tips']; //
                $customReport2Status = $res[2]['status']; // 考试状态
                $customReport2Tips = $res[2]['tips']; //
                $data = [
                    'total' => 1,
                    'current_page' => 1,
                    'per_page' => 10,
                    'last_page' => 1,
                    'data' => [
                        [
                            'title' => '定制报告技能测试考核',
                            'list' => [
                                [
                                    'type' => 1,
                                    'img' => $imgHost . '/mini/astrologer/test/5.png',
                                    'name' => '占星师测评-定制报告',
                                    'desc' => '您需要熟练掌握星盘、占星骰子、塔罗的相关知识，能独立输出自己的观点。',
                                    'tips' => '通过后获得定制报告及星盘问答接单资格',
                                    'is_passed' => $authStatus['custom_report'] === 1 ? 1 : 0,
                                    'list' => [
                                        [
                                            'id' => 1,
                                            'title' => '选择题',
                                            'status' => $customReport1Status ?? 2,
                                            'tips' => $customReport1Tips ?? '',
                                            'content' => [
                                                '选择题考核共40题，分单选及多选，答对35题则考核成功进入笔试考核',
                                                '选择题考核每题回答时间为60秒，若超时则当前题默认0分，自动进入下一道题',
                                                '选择题考核总时长为1小时，若超过规定时间未提交则所有超时的题，自动设置为0分',
                                                '考核如不通过则从考试结束时间开始计算间隔24小时才可继续重新考核',
                                            ],
                                        ],
                                        // [
                                        //     'id' => 2,
                                        //     'title' => '简答题',
                                        //     'status' => $customReport2Status ?? 2,
                                        //     'tips' => $customReport2Tips ?? '',
                                        //     'content' => [
                                        //         '1、占星师开始笔试考核后需要在特定星盘下回答指定问题，回复字数以及占星技法不限',
                                        //         '2、笔试考核总计时间为4小时，点击开始笔试考核后开始计时。若超过指定时间未提交则自动设置为0分',
                                        //         '3、提交回复后请占星师耐心等待，官方审核人员快马加鞭将在7个工作日内给予短信回复通知，请留意手机短信',
                                        //         '4、通过笔试考核后则可继续登录填写资料完成后续入驻流程',
                                        //     ],
                                        // ],
                                        [
                                            'id' => 3,
                                            'title' => '基础面试',
                                            'status' => $customReport2Status ?? 2,
                                            'tips' => $customReport2Tips ?? '',
                                            'content' => [],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                    'status' => 2,
                ];

                return show(config('code.success'), '请求成功', $data);
            }


            $data = [
                'total' => 1,
                'current_page' => 1,
                'per_page' => 10,
                'last_page' => 1,
                'data' => [],
                'status' => 1,
                'hint_data' => null,
            ];
            if ($this->isConsultAstro && $this->consultAccountInfo['team_id'])
            {
                $data['status'] = 3;
                $data['hint_data'] = [
                    'content' => '特邀咨询师暂不支持接收定制报告任务',
                    'desc' => '',
                ];
            }
            $astrModel = new ZlcrAstr();
            $customReportQuestionModel = new ZlcrCustomReportQuestion();

            $questionTaskList = [];
            if ($data['status'] === 1)
            {   // 不是咨询师  或者 咨询师没有团队
                // 获取用户正在进行中的任务
                $qids = $astrModel->getUnderwayTask($this->astrInfo['id']);
                foreach ($qids as $qid)
                {
                    $questionInfo = $customReportQuestionModel->getInfoById($qid);
                    $noteData = $astrQuestionNoteModel->getQuestionNote($this->astrInfo['id'], $qid);
                    $questionTaskList[] = [
                        'qid' => $qid,
                        // 'order_id' => $questionInfo['order_num'],// 订单id
                        'question' => $questionInfo['question_name'],// 用户问题
                        'astr_receiving_time' => $questionInfo['astr_receiving_time'],// 接单时间
                        'status' => $questionInfo['status'],// 问题状态
                        'qtype' => $questionInfo['qtype'],// 问题类型 1=>固定问题,2=>自定义问题
                        'is_merge' => $questionInfo['is_merge'],// 是否为合盘问题 0=>否,1=>是
                        'is_back' => 0,// 是否退款
                        'check_time1' => $questionInfo['check_time1'],// 问题审核时间
                        'check_time2' => $questionInfo['check_time2'],// 回答后审核时间
                        'answer_time' => $questionInfo['answer_time'],// 占星师解答时间
                        // 'tid' => (int)$questionInfo['id'],// 用户评价标签id
                        'earnings' => Util::getAstrCustomReportEarnings($questionInfo['order_num'], $this->astrInfo['proportion']),
                        // 'rate' => 4,// 用户评价星级🌟
                        // 'fadeback' => '算的好准，希望能帮助更多的人！',// 用户评价反馈文字
                        'note' => $noteData ? $noteData['note'] : '',// 占星师对该问题的备注
                        'type' => $questionInfo['get_way'] ?? 1,    // 1=>抢单 2=>派单
                    ];
                }
            }


            $data['data'] = $questionTaskList;
        } else
        {
            $map = [
                'q.astr_id' => (int)$this->astrInfo['id'],
            ];

            if (!empty($rangeTime))
            {
                $start_time = strtotime($rangeTime[0]);
                $end_time = strtotime($rangeTime[1]);
                $map['astr_receiving_time'] = ['between', [$start_time, $end_time]];
            } else if (($param['start_time'] && $param['end_time']))
            {
                $start_time = strtotime($param['start_time']);
                $end_time = strtotime($param['end_time']);
                if ($end_time < $start_time)
                {
                    return show(0, '开始时间不能大于结束时间！');
                } else
                {
                    $map['astr_receiving_time'] = ['between', [$start_time, $end_time]];
                }

            } else if ($param['start_time'])
            {
                $start_time = strtotime($param['start_time']);
                $map['astr_receiving_time'] = ['>=', $start_time];
            } else if ($param['end_time'])
            {
                $map['astr_receiving_time'] = ['<', strtotime($param['start_time'])];
            }

            if (!empty($qtype))
            {
                foreach ($qtype as $k => $v)
                {
                    $qtype[$k] = (int)$v;
                }
                $map['q.qtype'] = ['in', $qtype];
            }

            if ($param['status'])
            {
                if (is_array($param['status']['status']))
                {
                    foreach ($param['status']['status'] as $k => $v)
                    {
                        $param['status']['status'][$k] = (int)$v;
                    }
                    if ($param['status']['status'][0] === 5)
                    {// 如果是已完成，那么把评价待审核和已评价也加上
                        $param['status']['status'][] = 6;
                        $param['status']['status'][] = 7;
                    }
                    $map['q.status'] = ['in', $param['status']['status']];
                } else
                {
                    $status = [];
                    foreach ($param['status'] as $k => $v)
                    {
                        $status[] = (int)$v;
                    }
                    if ($status[0] === 5)
                    {// 如果是已完成，那么把评价待审核和已评价也加上
                        $status[] = 6;
                        $status[] = 7;
                    }
                    $map['q.status'] = ['in', $status];
                }

            }

//            if (!empty($status))
//            {
//                if (is_array($status))
//                {
//                    foreach ($status as $k => $v)
//                    {
//                        $status[$k] = (int)$v;
//                    }
//                    $map['status'] = ['in', $status];
//                } else
//                {
//                    $status_in = [];
//                    foreach ($status as $k => $v)
//                    {
//                        $status_in[] = (int)$v;
//                    }
//                    $map['status'] = ['in', $status_in];
//                }
//
//
//            }
            // 按问题名称搜索
            if ($question !== '')
            {
                $map['q.question_name'] = ['like', '%' . $question . '%'];
            }

            $data = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->alias('q')
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
                ->field('q.id qid,q.answer_time,q.astr_receiving_time,q.check_time1,q.check_time2,q.is_back,q.is_merge,q.qtype,q.question_name question,q.status,q.tid,a.amount earnings,a.type zlcr_astr_account_record_type')
                ->where($map)
                ->order($sort)
                ->paginate($limit, false, ['page' => $page])
                ->toArray();

            $qids = array_column($data['data'], 'qid');
//            $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.status,c.comment,c.appeal_status,c.create_time,t.tag_name tname', 'c.qid');
            $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.tid,t.tag_name tname,t.score', 'c.qid');
            foreach ($data['data'] as $key => $dataItem)
            {
                $noteData = $astrQuestionNoteModel->getQuestionNote($this->astrInfo['id'], $dataItem['qid']);
                $data['data'][$key]['note'] = $noteData ? $noteData['note'] : '';

                if ((int)$dataItem['zlcr_astr_account_record_type'] === 3)
                {
                    $data['data'][$key]['earnings'] = 0;
                    $data['data'][$key]['status'] = 17;
                }
                unset($data['data'][$key]['zlcr_astr_account_record_type']);

//                $data['data'][$key]['comment_data'] = null;
//                if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
//                {
//                    if ($commentList[$dataItem['qid']]['appeal_status'])
//                    {
//                        $level = 3;
//                        $comment = '平淡无味';
//                    } else
//                    {
//                        $level = (int)$commentList[$dataItem['qid']]['level'];
//                        $comment = (int)$commentList[$dataItem['qid']]['status'] === 3 ? '' : $commentList[$dataItem['qid']]['comment'];
//                    }
                if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
                {
                    $data['data'][$key]['rate'] = (int)$commentList[$dataItem['qid']]['level']; // 标签星级
                    $data['data'][$key]['tname'] = $commentList[$dataItem['qid']]['tname']; // 标签名字
                    $data['data'][$key]['grade_change'] = $commentList[$dataItem['qid']]['score']; // 变动能力值
                } else
                {
                    $data['data'][$key]['rate'] = 0;
                    $data['data'][$key]['tname'] = '';
                }

//                    $data['data'][$key]['comment_data'] = [
//                        'level' => $level,
//                        'comment' => $comment,
//                        'create_time' => (int)$commentList[$dataItem['qid']]['create_time'],
//                        'tname' => $commentList[$dataItem['qid']]['tname'],
//                    ];
//                }
            }
        }


        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取可领取任务数量
     * @throws Exception
     */
    public function getTaskNum()
    {
        // 是否是特邀咨询师
        $isConsultAstro = $this->isConsultAstro && $this->consultAccountInfo['team_id'];
        if (!isset($this->astrInfo['extend']['is_complete_information']) || $isConsultAstro)
        {   // 未补全信息 或者 是特邀咨询师
            return show(config('code.success'), '请求成功', [
                'question_num' => 0,
                'task_list_update' => 0,
                'show_dialog' => '',
                'dialog_title' => '',
                'dialog_msg' => '',
                'dialog_btn' => '',
                'target' => '',
                'link' => '',
            ]);
        } else
        {
            $astrModel = new ZlcrAstr();
            // 获取用户正在进行中的任务
            $qids = $astrModel->getUnderwayTask($this->astrInfo['id']);
            $zlcrCustomReportQuestionModel = new ZlcrCustomReportQuestion();
            if ($qids)
            {
                $questionNUm = 0;
            } else
            {
                // 弃答问题ID
                $notAnswerQids = (new ZlcrAstrNotAnswerQuestion())->getNotAnswerQids($this->astrInfo['id']);
                // 获取可接任务数量
                $questionNUm = $zlcrCustomReportQuestionModel->getCustomReportQueueNum($notAnswerQids);
            }

            $resData = [
                'question_num' => $questionNUm,
                'task_list_update' => 0,
                'show_dialog' => '',
                'dialog_title' => '',
                'dialog_msg' => '',
                'dialog_btn' => '',
                'target' => '',
                'link' => '',
            ];

            // 获取 历史qids
            $oldQids = $astrModel->getOldUnderwayTask($this->astrInfo['id']);

            if ($oldQids !== $qids)
            {   // 更新 问题ID 信息
                $astrModel->setOldUnderwayTask($this->astrInfo['id'], $qids);
                // 获取
                foreach ($oldQids as $oldQid)
                {
                    if (in_array($oldQid, $qids, true))
                    {
                        continue;
                    }

                    $questionInfo = $zlcrCustomReportQuestionModel->getInfoById($oldQid, ['status', 'astr_id']);
                    if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
                    {
                        continue;
                    }
                    if ((int)$questionInfo['status'] === 15)
                    {
                        $resData['show_dialog'] = 1;
                        $resData['dialog_title'] = '订单已强制取消';
                        $resData['dialog_msg'] = '非常抱歉，因用户取消订单，此订单已失效，此订单金额的10%作为您的补偿金，请您到历史收益中查看';
                        $resData['dialog_btn'] = '历史收益';
                        $resData['target'] = 'local';
                        $resData['link'] = '/earnings/list';
                        $resData['qid'] = $oldQid;
                    }
                }

                $resData['task_list_update'] = 1;
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }
}
